package com.zq.assistant.ui.main;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;

import com.zq.assistant.R;
import com.zq.assistant.bean.FileInfo;
import com.zq.assistant.bean.ResultList;
import com.zq.assistant.func.api.FileAPI;
import com.zq.assistant.func.apifactory.APIFactory;
import com.zq.assistant.func.apifactory.callback.ResultCallback;
import com.zq.assistant.func.db.DBHelper;

import com.zq.assistant.ui.BaseActivity;
import com.zq.assistant.ui.file.FileDownloadManagerActivity;
import com.zq.assistant.ui.main.adpter.FileExploreAdapter;
import com.zq.assistant.ui.settings.SettingsActivity;
import com.zq.assistant.ui.test.InjectorTestActivity;
import com.zq.assistant.ui.widget.recyclerview.multi.MultiRecyclerView;
import com.zq.assistant.ui.widget.recyclerview.OnItemClickListener;
import com.zq.assistant.ui.widget.recyclerview.divider.RecyclerViewDivider;
import com.zq.assistant.utils.DialogUtils;
import com.zq.assistant.utils.PaginationHelper;
import com.zq.assistant.utils.URLUtils;
import com.zq.download.DownloadManager;

import java.util.ArrayList;
import java.util.Stack;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class MainActivity extends BaseActivity implements PaginationHelper.LoadCallback, OnItemClickListener {

    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.multi_recycler_view)
    MultiRecyclerView multiRecyclerView;

    private PaginationHelper paginationHelper = new PaginationHelper();
    private FileExploreAdapter fileExploreAdapter;

    private String currentPath = "/";

    private Stack<String> pathStack = new Stack<>();
    private ListPopupWindow listPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        initToolbar(this,toolbar);

        multiRecyclerView.addItemDecoration(new RecyclerViewDivider(getResources().getDrawable(R.drawable.timg), 10));
        multiRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        paginationHelper.setupWithMultiRecyclerView(multiRecyclerView, this);

        fileExploreAdapter = new FileExploreAdapter(null, MainActivity.this);
        fileExploreAdapter.setOnItemClickListener(MainActivity.this);

        multiRecyclerView.setAdapter(fileExploreAdapter);

        paginationHelper.refresh();

//        List<User> oldList = DBUtils.getDao(User.class).query(new String[]{"userId"}, null, null, null, null, "userId DESC", "0,1");
//
//        if(oldList == null || oldList.isEmpty()){
//            return;
//
//        }
//
//        long startTime = System.currentTimeMillis();
//        List<User> userList = new ArrayList<>();
//        for (int i = 10000; i < 20000; i++) {
//
//            User user = new User();
//            user.setUserId(i + "");
//            user.setName("ssssssssssssss");
//            user.setPwd("agregresgrvre324321312/.");
//            user.setBirthday(new Date(System.currentTimeMillis()));
//            user.setAge(122);
//            user.setMan(false);
//            user.setHead(new byte[]{1, 23, 22, 'a', 'z', '_', '/', '?'});
//            userList.add(user);
//        }
//        DBUtils.getDao(User.class).insert(userList);
//
//        Logger.get().i("Test", "=====插入10000耗时=======" + (System.currentTimeMillis() - startTime));


//        DownloadManager
//                .get()
//                .download("http://180.153.100.153/mmgr.myapp.com/msoft/sec/secure/" +
//                        "GodDresser/1/2/3/102085/tencentmobilemanager_20170619165233_7.1.0_android_build4035_102085.apk" +
//                        "?mkey=594a1a7011b18941&f=9512&c=0&p=.apk",
//                        new DBHelper(this));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.settings:

                SettingsActivity.start(this);
               return true;
            case R.id.test_cell_adapter:

                CellAdapterTestActivity.start(this);
                return true;
            case R.id.test_injector:

                InjectorTestActivity.start(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(RecyclerView.ViewHolder holder, int position) {

        final FileInfo fileBean = fileExploreAdapter.getDataAt(position);

        if (fileBean.getType() == FileInfo.TYPE_DIRECTORY) {

            pathStack.push(currentPath);
            currentPath = fileBean.getPath();
            paginationHelper.refresh();
        } else if (fileBean.getType() == FileInfo.TYPE_FILE) {

            ArrayList<String> itemList = new ArrayList<>();
            itemList.add("下载");
            itemList.add("查看下载");
            listPopupWindow = DialogUtils.showList(this, holder.itemView, itemList, new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    listPopupWindow.dismiss();
                    if (position == 0) {

                        final String url = URLUtils.getFileDownloadUrl(fileBean.getPath());

                        DownloadManager
                                .get()
                                .download(url,
                                        new DBHelper(MainActivity.this));

//                        final String url = URLUtils.getFileDownloadUrl(fileBean.getPath());
//                        DownloadInfo downloadInfo = new DownloadInfo();
//                        downloadInfo.setUrl(url);
//
//                        getContentResolver().insert(FileDownloadProvider.CONTENT_URI,
//                                AndroidSQLiteDaoImpl.sqlBeanToContentValues(downloadInfo));
//
//                        OKHttpUtils.download(url,
//                                PathManager.get().getBaseDir().getAbsolutePath(),
//                                null,
//                                new FileTransferListener() {
//                                    @Override
//                                    public void onStart(String url, String fileName, String filePath) {
//
//                                        DownloadInfo downloadInfo = new DownloadInfo();
//                                        downloadInfo.setUrl(url);
//                                        downloadInfo.setFileName(fileName);
//                                        downloadInfo.setFilePath(filePath);
//
//                                        getContentResolver().update(FileDownloadProvider.CONTENT_URI,
//                                                AndroidSQLiteDaoImpl.sqlBeanToContentValues(downloadInfo),
//                                                "url = ?",
//                                                new String[]{url});
//                                    }
//
//                                    @Override
//                                    public void onTransfer(long contentLength, long currentLength) {
//
//                                        DownloadInfo downloadInfo = new DownloadInfo();
//                                        downloadInfo.setContentLength((int) contentLength);
//                                        downloadInfo.setCurrentLength((int) currentLength);
//
//                                        getContentResolver().update(FileDownloadProvider.CONTENT_URI,
//                                                AndroidSQLiteDaoImpl.sqlBeanToContentValues(downloadInfo),
//                                                "url = ?",
//                                                new String[]{url});
//                                    }
//
//                                    @Override
//                                    public void onFinish(String url) {
//                                    }
//                                });
                    } else if (position == 1) {

                        FileDownloadManagerActivity.start(MainActivity.this);
                    }
                }
            });
        }
    }

    @Override
    public void onBackPressed() {

        if (pathStack.size() > 0) {
            currentPath = pathStack.pop();
            paginationHelper.refresh();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onLoadData(int page) {

        APIFactory.get(FileAPI.class).bindLifeCycle(this).getFileList(currentPath, new ResultCallback<ResultList<FileInfo>>() {
            @Override
            public void onSuccess(ResultList<FileInfo> result) {

                paginationHelper.setRefreshSuccess();
                fileExploreAdapter.setDataList(result.getDataList());
            }

            @Override
            public void onFail(int errorCode, String message) {

                paginationHelper.setRefreshFail();

                if (fileExploreAdapter == null || fileExploreAdapter.isEmpty()) {
                    multiRecyclerView.setAdapter(null);
                }
            }
        });
    }

    @Override
    public void onLoadMoreData(int page) {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                paginationHelper.setLoadMoreFail();
            }
        }, 500);
    }

    @Override
    public void stopLoad(int page) {

    }
}
